package com.xing.server.service.impl;

import com.xing.server.base.R;
import com.xing.server.pojo.Department;
import com.xing.server.mapper.DepartmentMapper;
import com.xing.server.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xingfuhao
 * @since 2021-11-28
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {


    @Resource
    private  DepartmentMapper departmentMapper;

    /**
     * 获取所有部门
     * @return
     */
    @Override
    public List<Department> getAllDepartment() {
        return departmentMapper.getAllDepartments(-1);
    }

    /**
     * 添加部门
     * @param department
     * @return
     */
    @Override
    public R addDepartment(Department department) {
        department.setEnabled(true);
        departmentMapper.addDep(department);
        if(1==department.getResult()){
            department = departmentMapper.selectById(department.getId());
            return R.success("添加成功！",department);
        }
        return R.error("添加失败！");
    }

    /**
     * 删除部门
     * @param id
     * @return
     */
    @Override
    public R deleteDepartment(Integer id) {
//        //不能这样删除的，这样准定是错的，因为部门下面还有人，不能直接删除的
//        int i = departmentMapper.deleteById(id);
//        if(i>0){
//            return R.success("删除成功");
//        }
//        return R.error("删除失败");

        Department department = new Department();
        department.setId(id);
        departmentMapper.deleteDep(department);
        if(-2==department.getResult()){
            return R.error("该部门还有子部门，删除失败");
        }
        if(-1==department.getResult()){
            return R.error("该部门下还有员工，删除失败");
        }
        if(1==department.getResult()){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }
}
